<template>
  <div>
    <div class="table-page-search">
      <a-form>
        <a-form-item label="账号">
          <a-input placeholder="请输入" v-model="queryParam.loginName" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model="queryParam.status">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value="'0'">正常</a-select-option>
            <a-select-option :value="'1'">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <span class="search-submitButtons">
          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <a-button @click="() => (queryParam = { status: '' })">重置</a-button>
        </span>
      </a-form>
    </div>
    <div class="table-operator disFlxJS">
      <div>
        <a-button v-has="'system:user:add'" type="primary" @click="$refs.modal.add()">新建</a-button>
        <a-button v-has="'system:user:add'" @click="$refs.ImportAdminList.moduleShow()">导入管理员</a-button>
        <a-button v-has="'system:user:export'" @click="excelDown">导出</a-button>
        <a-dropdown v-has="'system:user:remove'" v-if="selectedRowKeys.length > 0">
          <a-button type="danger" icon="delete" @click="delByIds(selectedRowKeys)">删除</a-button>
        </a-dropdown>
      </div>
      <CustomTable :name="$route.name + '_' + 'SystemUser'" :columns="columns" :newColumns="newColumns" />
    </div>
    <s-table size="default" ref="table" rowKey="userId" :columns="newColumns" :data="loadData" :rowSelection="null">
      <!-- 管理员信息 -->
      <template slot="userInfo" slot-scope="text, record, index">
        <div class="disFlxAC">
          <a-avatar size="default" icon="user" :src="record.avatar" />
          <div class="_pl-10 fz-12">
            <div>{{ record.userName }}</div>
            <div>{{ record.phonenumber }}</div>
          </div>
        </div>
      </template>

      <span slot="status" slot-scope="text, record">
        <a-switch :disabled="!record.edit" :checked="record.status == '0'" @change="onChangeStatus(record)" />
      </span>

        <!-- 小程序登录 -->
        <!-- <template slot="isLoginFilter" slot-scope="text, record, index">
          <FilterCheckbox
            v-model="queryParam.isLogin"
            :options="
              Dict.getLocal('isLoginDict').map(v => {
                return { value: v.dictValue, label: v.dictLabel }
              })
            "
            @search="handleSearch"
          />
        </template> -->
        <span slot="isLogin" slot-scope="text">
          <DictTag :options="Dict.getLocal('isLoginDict')" :value="text" isText />
        </span>

        <!-- 公众号关注状态 -->
        <!-- <template slot="isOfficialAccountFilter" slot-scope="text, record, index">
          <FilterCheckbox
            v-model="queryParam.isOfficialAccount"
            :options="
              Dict.getLocal('isOfficialAccountDict').map(v => {
                return { value: v.dictValue, label: v.dictLabel }
              })
            "
            @search="handleSearch"
          />
        </template> -->
        <span slot="isOfficialAccount" slot-scope="text">
          <DictTag :options="Dict.getLocal('isOfficialAccountDict')" :value="text" isText />
        </span>


      <span slot="action" slot-scope="text, record">
        <a-button
          v-has="'system:user:edit'"
          type="primary"
          ghost
          size="small"
          class="_mr-5"
          @click="handleEdit(record)"
        >
          编辑
        </a-button>
        <a-button
          v-has="'system:user:remove'"
          v-if="record.edit && record.userId !== 1"
          type="primary"
          ghost
          size="small"
          class="_mr-5"
          @click="delByIds([record.userId])"
        >
          删除
        </a-button>
        <a-button
          v-has="'system:user:resetPwd'"
          type="primary"
          ghost
          size="small"
          class="_mr-5"
          @click="resetPwd(record)"
        >
          重置密码
        </a-button>
        <a-button
          v-has="'system:user:relevance'"
          type="primary"
          ghost
          size="small"
          class="_mr-5"
          @click="setMenber(record)"
        >
          {{ record.leadingId ? '解除关联' : '关联会员' }}
        </a-button>
      </span>
    </s-table>
    <user-modal ref="modal" @ok="handleOk" @reload="handleReload" :deptTree="deptTree" />
    <user-pwd-modal ref="pwdmodal" />

    <ImportAdminList ref="ImportAdminList" @success="handleOk" />
    <SearchMember ref="SearchMember" @success="handleReload" />
  </div>
</template>

<script>
import { Tree } from 'ant-design-vue'
import { STable } from '@/components'
import {
  getUserList,
  getDeptList,
  delUser,
  changUserStatus,
  userExportExcel,
  leadingMemberDel
} from '@/api/system/system'
import UserModal from './modules/UserModal'
import UserPwdModal from './modules/UserPwdModal'
import pick from 'lodash.pick'
import CustomTable from '@/components/Cuscolumn'
import ImportAdminList from './components/importAdminList'
import SearchMember from '@/components/UserComponents/searchMember.vue'
import DictTag from '@/components/DictTag'
import FilterCheckbox from '@/components/Table/filterCheckbox'
export default {
  name: 'TableList',
  components: {
    Tree,
    STable,
    UserModal,
    UserPwdModal,
    CustomTable,
    ImportAdminList,
    SearchMember,
    DictTag,
    FilterCheckbox
  },
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: { status: '' },
      // 表头
      columns: [
        {
          title: '账号',
          dataIndex: 'loginName',
          width: '200px'
        },
        {
          title: '管理员信息',
          dataIndex: 'userInfo',
          scopedSlots: { customRender: 'userInfo' },
          width: '200px',
          ellipsis: true,
          align: 'left'
        },
        // {
        //   title: '邮箱',
        //   dataIndex: 'email',
        //   width: '200px'
        // },
        {
          title: '角色',
          dataIndex: 'roleName',
          width: '100px'
        },
        {
          title: '关联用户',
          dataIndex: 'memberName',
          width: '150px',
          ellipsis: true
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          width: '100px'
        },
        {
          title: '小程序',
          dataIndex: 'isLogin',
          width: '120px',
          scopedSlots: { customRender: 'isLogin', filterDropdown: 'isLoginFilter' }
        },
        {
          title: '公众号',
          dataIndex: 'isOfficialAccount',
          width: '140px',
          scopedSlots: { customRender: 'isOfficialAccount', filterDropdown: 'isOfficialAccountFilter' }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: '180px',
          sorter: true
        },
        {
          title: '操作',
          width: '300px',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getUserList(Object.assign(parameter, this.queryParam)).then(res => {
          console.log('getUserList', res)
          return res
        })
      },
      searchValue: '',
      deptTree: [],
      expandedKeys: [],
      dataList: [],
      autoExpandParent: true,
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    newColumns() {
      const currentColumns = this.$store.state.user.customTable
      if (currentColumns && currentColumns[this.$route.name + '_' + 'SystemUser']) {
        return this.$options
          .data()
          .columns.filter(v => {
            const _items = currentColumns[this.$route.name + '_' + 'SystemUser'].find(
              item => item === v.title || item.title === v.title
            )
            if (_items) return Object.assign(v, _items)
          })
          .sort((a, b) => {
            return a.tableSort - b.tableSort
          })
      } else {
        return this.columns
      }
    }
  },
  created() {
    getDeptList().then(res => {
      const data = res.rows
      this.buildtree(data, this.deptTree, 0)
      this.expandedKeys = data.map(m => m.parentId)
      this.dataList = data.map(m => {
        return { key: m.deptId, title: m.deptName }
      })
    })
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    handleEdit(record) {
      this.$refs.modal.edit(record)
    },
    resetPwd(record) {
      this.$refs.pwdmodal.edit(record)
    },
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleOk() {
      this.$refs.table.refresh(true)
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    delByIds(ids) {
      var _this = this
      this.$confirm({
        title: '管理员删除?',
        content: '是否确定删除该管理员?',
        onOk() {
          delUser({ ids: ids.join(',') }).then(res => {
            if (res.code === 0) {
              _this.$message.success(`删除成功`)
              _this.handleReload()
            } else {
              _this.$message.error(res.msg)
            }
            // const difference = new Set(this.selectedRowKeys.filter(x => !new Set(ids).has(x)))
            // this.selectedRowKeys = Array.from(difference)
            // this.selectedRowKeys = []
          })
        },
        onCancel() {}
      })
    },
    onChangeStatus(record) {
      record.status = record.status === '0' ? '1' : '0'
      changUserStatus(pick(record, 'userId', 'status')).then(res => {
        if (res.code === 0) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.msg)
        }
      })
      // 发送状态到服务器
    },
    buildtree(list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.deptId,
            value: item.deptId, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildtree(list, child.children, item.deptId)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    },
    // 下面是树相关方法
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    emitEmpty() {
      this.$refs.searchInput.focus()
      this.searchValue = ''
      this.searchDept()
    },
    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },
    handleChange(e) {
      this.searchDept()
    },
    searchDept() {
      const value = this.searchValue
      const expandedKeys = this.dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            const parentKey = this.getParentKey(item.key, this.deptTree)
            return parentKey
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        autoExpandParent: true
      })
    },
    // 导出
    excelDown() {
      userExportExcel(this.queryParam)
    },
    // 关联会员
    setMenber(row) {
      const _that = this
      if (row.leadingId) {
        _that.$confirm({
          title: '确认解除?',
          content: '解除后将于关联会员无任何关系,确认解除吗?',
          centered: true,
          onOk() {
            return new Promise((resolve, reject) => {
              leadingMemberDel({ ids: row.leadingId })
                .then(res => {
                  _that.$message.success(`已成功解除关联`)
                  _that.handleReload()
                  resolve(res)
                })
                .catch(error => {
                  reject(error)
                })
            })
          }
        })
      } else {
        _that.$refs.SearchMember.show({
          name: row.userName,
          phone: row.phonenumber,
          avatar: row.avatar,
          socialPosition: ''
        })
      }
    }
  }
}
</script>
